<template>
  <div class="product-detail-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商品详情</span>
          <el-button type="primary" size="small" @click="goBack">返回列表</el-button>
        </div>
      </template>

      <el-skeleton :rows="10" animated v-if="loading" />

      <div v-else>
        <!-- 基本信息 -->
        <div class="basic-info">
          <div class="product-images">
            <el-image 
              :src="productInfo.image" 
              fit="cover"
              style="width: 300px; height: 300px; border: 1px solid #eee;"
            />
            <div class="image-list" v-if="productInfo.images && productInfo.images.length">
              <el-image 
                v-for="(img, index) in productInfo.images" 
                :key="index"
                :src="img" 
                fit="cover"
                style="width: 80px; height: 80px; margin-right: 10px; border: 1px solid #eee;"
                @click="productInfo.image = img"
              />
            </div>
          </div>

          <div class="product-info">
            <h2>{{ productInfo.name }}</h2>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="商品ID">{{ productInfo.id }}</el-descriptions-item>
              <el-descriptions-item label="商品分类">{{ productInfo.category }}</el-descriptions-item>
              <el-descriptions-item label="价格">
                <span class="price">¥{{ Number(productInfo.price).toFixed(2) }}</span>
                <span class="original-price" v-if="productInfo.originalPrice">¥{{ Number(productInfo.originalPrice).toFixed(2) }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="库存">{{ productInfo.stock }}</el-descriptions-item>
              <el-descriptions-item label="销量">{{ productInfo.sales }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="productInfo.status === 'on' ? 'success' : 'info'">
                  {{ productInfo.status === 'on' ? '上架' : '下架' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ productInfo.createTime }}</el-descriptions-item>
              <el-descriptions-item label="更新时间">{{ productInfo.updateTime }}</el-descriptions-item>
            </el-descriptions>

            <div class="action-buttons">
              <el-button type="primary" @click="handleEdit">编辑商品</el-button>
              <el-button 
                :type="productInfo.status === 'on' ? 'info' : 'success'" 
                @click="handleToggleStatus"
              >
                {{ productInfo.status === 'on' ? '下架' : '上架' }}商品
              </el-button>
              <el-button type="danger" @click="handleDelete">删除商品</el-button>
            </div>
          </div>
        </div>

        <!-- 商品简介 -->
        <el-card class="detail-section" shadow="never">
          <template #header>
            <div class="section-header">
              <span>商品简介</span>
            </div>
          </template>
          <p>{{ productInfo.brief || '暂无简介' }}</p>
        </el-card>

        <!-- 商品规格 -->
        <el-card class="detail-section" shadow="never">
          <template #header>
            <div class="section-header">
              <span>商品规格</span>
            </div>
          </template>
          <el-table :data="productInfo.specs || []" style="width: 100%" v-if="productInfo.specs && productInfo.specs.length">
            <el-table-column prop="name" label="规格名称" />
            <el-table-column prop="price" label="价格">
              <template #default="scope">
                ¥{{ Number(scope.row.price).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" />
          </el-table>
          <el-empty v-else description="暂无规格信息" />
        </el-card>

        <!-- 商品详情 -->
        <el-card class="detail-section" shadow="never">
          <template #header>
            <div class="section-header">
              <span>商品详情</span>
            </div>
          </template>
          <div v-if="productInfo.detail" class="product-detail-content">
            {{ productInfo.detail }}
          </div>
          <el-empty v-else description="暂无详情信息" />
        </el-card>

        <!-- 销售记录 -->
        <el-card class="detail-section" shadow="never">
          <template #header>
            <div class="section-header">
              <span>销售记录</span>
            </div>
          </template>
          <el-table :data="salesRecords" style="width: 100%">
            <el-table-column prop="orderId" label="订单号" width="180" />
            <el-table-column prop="username" label="购买用户" width="120" />
            <el-table-column prop="quantity" label="购买数量" width="100" />
            <el-table-column prop="spec" label="规格" width="120" />
            <el-table-column prop="price" label="价格" width="100">
              <template #default="scope">
                ¥{{ Number(scope.row.price).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="totalAmount" label="总金额" width="100">
              <template #default="scope">
                ¥{{ Number(scope.row.totalAmount).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="购买时间" />
          </el-table>
          <div class="pagination-container" v-if="salesRecords.length > 0">
            <el-pagination
              v-model:current-page="salesCurrentPage"
              v-model:page-size="salesPageSize"
              :page-sizes="[5, 10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="salesTotal"
              @size-change="handleSalesSizeChange"
              @current-change="handleSalesCurrentChange"
            />
          </div>
          <el-empty v-if="salesRecords.length === 0" description="暂无销售记录" />
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getProductDetail, changeProductStatus, deleteProduct } from '@/api/shop'

const route = useRoute()
const router = useRouter()
const loading = ref(true)
const productId = route.params.id

// 商品信息
const productInfo = ref({
  id: '',
  name: '',
  category: '',
  image: '',
  images: [],
  price: 0,
  originalPrice: 0,
  stock: 0,
  sales: 0,
  status: '',
  brief: '',
  detail: '',
  specs: [],
  createTime: '',
  updateTime: ''
})

// 销售记录
const salesRecords = ref([])
const salesCurrentPage = ref(1)
const salesPageSize = ref(10)
const salesTotal = ref(0)

// 获取商品详情
const fetchProductDetail = async () => {
  loading.value = true
  try {
    // 实际应用中应该调用API
    // const { data } = await getProductDetail(productId)
    // productInfo.value = data
    
    // 模拟数据
    setTimeout(() => {
      productInfo.value = {
        id: productId,
        name: `商品${productId}`,
        category: '中药材',
        image: `https://via.placeholder.com/300?text=商品${productId}`,
        images: [
          `https://via.placeholder.com/300?text=商品${productId}-1`,
          `https://via.placeholder.com/300?text=商品${productId}-2`,
          `https://via.placeholder.com/300?text=商品${productId}-3`
        ],
        price: 199.00,
        originalPrice: 299.00,
        stock: 500,
        sales: 200,
        status: 'on',
        brief: `这是商品${productId}的简介，描述了这个商品的基本特点和用途。`,
        detail: `这是商品${productId}的详细描述，包含了产品的功效、用法用量、注意事项等详细信息。这里可以包含很多专业的描述，帮助用户了解商品的各种特性和优势。`,
        specs: [
          { name: '规格1', price: 199.00, stock: 200 },
          { name: '规格2', price: 249.00, stock: 150 },
          { name: '规格3', price: 299.00, stock: 100 }
        ],
        createTime: '2023-05-01 10:00:00',
        updateTime: '2023-05-10 15:30:00'
      }
      loading.value = false
      fetchSalesRecords()
    }, 500)
  } catch (error) {
    console.error('获取商品详情失败', error)
    ElMessage.error('获取商品详情失败')
    loading.value = false
  }
}

// 获取销售记录
const fetchSalesRecords = () => {
  // 实际应用中应该调用API
  // 模拟数据
  setTimeout(() => {
    const mockSalesRecords = Array.from({ length: 20 }).map((_, index) => ({
      orderId: `ORD20230501${1000 + index}`,
      username: `用户${index + 1}`,
      quantity: Math.floor(Math.random() * 5) + 1,
      spec: productInfo.value.specs[Math.floor(Math.random() * productInfo.value.specs.length)].name,
      price: productInfo.value.price,
      totalAmount: (productInfo.value.price * (Math.floor(Math.random() * 5) + 1)).toFixed(2),
      createTime: `2023-05-${10 + index} 10:00:00`
    }))
    
    salesRecords.value = mockSalesRecords.slice(
      (salesCurrentPage.value - 1) * salesPageSize.value,
      salesCurrentPage.value * salesPageSize.value
    )
    salesTotal.value = mockSalesRecords.length
  }, 300)
}

// 分页处理
const handleSalesSizeChange = (val) => {
  salesPageSize.value = val
  fetchSalesRecords()
}

const handleSalesCurrentChange = (val) => {
  salesCurrentPage.value = val
  fetchSalesRecords()
}

// 返回列表
const goBack = () => {
  router.push('/shop/products')
}

// 编辑商品
const handleEdit = () => {
  router.push(`/shop/products/edit/${productId}`)
}

// 切换商品状态
const handleToggleStatus = () => {
  const statusText = productInfo.value.status === 'on' ? '下架' : '上架'
  ElMessageBox.confirm(`确定要${statusText}该商品吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 实际应用中应该调用API
      // await changeProductStatus(productId, productInfo.value.status === 'on' ? 'off' : 'on')
      
      // 模拟成功
      ElMessage({
        type: 'success',
        message: `${statusText}成功`
      })
      
      // 修改本地数据
      productInfo.value.status = productInfo.value.status === 'on' ? 'off' : 'on'
    } catch (error) {
      console.error('操作失败', error)
      ElMessage({
        type: 'error',
        message: '操作失败'
      })
    }
  }).catch(() => {})
}

// 删除商品
const handleDelete = () => {
  ElMessageBox.confirm('确定要删除该商品吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 实际应用中应该调用API
      // await deleteProduct(productId)
      
      // 模拟成功
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      
      // 返回列表页
      router.push('/shop/products')
    } catch (error) {
      console.error('删除失败', error)
      ElMessage({
        type: 'error',
        message: '删除失败'
      })
    }
  }).catch(() => {})
}

// 页面加载时获取商品详情
onMounted(() => {
  fetchProductDetail()
})
</script>

<style lang="scss" scoped>
.product-detail-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .basic-info {
    display: flex;
    margin-bottom: 30px;
    
    .product-images {
      margin-right: 30px;
      
      .image-list {
        display: flex;
        margin-top: 15px;
        overflow-x: auto;
      }
    }
    
    .product-info {
      flex: 1;
      
      h2 {
        margin-top: 0;
        margin-bottom: 20px;
      }
      
      .price {
        color: #f56c6c;
        font-size: 20px;
        font-weight: bold;
        margin-right: 10px;
      }
      
      .original-price {
        color: #909399;
        text-decoration: line-through;
      }
      
      .action-buttons {
        margin-top: 20px;
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .detail-section {
    margin-bottom: 20px;
    
    .section-header {
      font-weight: bold;
    }
    
    .product-detail-content {
      white-space: pre-wrap;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 